package com.auto.code.controller;

import com.auto.code.domain.DBInfoDTO;
import com.auto.code.domain.ResultInfo;
import com.auto.code.service.DBInfoService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 数据库管理
 */
@Controller
@RequestMapping("/auto/code/dbInfo")
public class DBInfoController {
	@Autowired
    private DBInfoService dbInfoService;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
    public ModelAndView list(HttpServletRequest request) {
        return new ModelAndView("/page/db/db_list");
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public ModelAndView tableList(Model model, DBInfoDTO dbInfoDTO) {
        PageInfo<DBInfoDTO> pageList = dbInfoService.queryPage(dbInfoDTO);
        model.addAttribute("pageInfo", pageList);
        return new ModelAndView("/page/db/db_table_list");
    }

    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public ModelAndView createPage(Model model, DBInfoDTO dbInfoDTO) {
        return new ModelAndView("/page/db/db_create");
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo createSave(Model model, DBInfoDTO dbInfoDTO) {
        dbInfoService.create(dbInfoDTO);
        return  ResultInfo.ok();
    }

    @RequestMapping(value = "/del", method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo del(@RequestParam(required = false, value = "idList[]") List<Long> idList) {
	    for (Long id : idList){
            dbInfoService.deleteById(id);
        }
        return ResultInfo.ok();
    }

    @RequestMapping(value = "/modify", method = RequestMethod.GET)
    public ModelAndView modifyPage(Model model, Long id) {
        model.addAttribute("dbInfo", dbInfoService.getById(id));
        return new ModelAndView("/page/db/db_modify");
    }

    @RequestMapping(value = "/modify", method = RequestMethod.POST)
    @ResponseBody
    public ResultInfo modifySave(Model model, DBInfoDTO dbInfoDTO) {
        dbInfoService.update(dbInfoDTO);
        return  ResultInfo.ok();
    }

}
